Author:
Posted: 3/29/2006 12:19:55 PM
Sitecore version: tested with 5.1.1.11
The Solution:
Use the code below to solve the problem
1) Add event to “item:added”
<event name="item:added">
<handler type="PreventDouble.AddedEventHandler, PreventDouble" method="OnItemAdded"/>
</event>
2) Here is the code:
using System;
using Sitecore;
using Sitecore.Configuration;
using Sitecore.Events;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Pipelines.Save;
namespace PreventDouble
{
publicclass AddedEventHandler
{
publicvoid OnItemAdded(object obj, EventArgs args)
{
Item itm = Event.ExtractParameter(args, 0) as Item;
if ( itm.Database.Name == "master" )
{
Database database = Factory.GetDatabase("master");
Item existItm = database.Items[itm.Paths.Path];
SitecoreEventArgs evt = args as SitecoreEventArgs;
if (existItm.ID != itm.ID)
{
Sitecore.Context.ClientPage.ClientResponse.Eval("alert('You cannot create item with the same name!')");
itm.Delete();
evt.Result.Cancel = true;
}
}
}
}
}
For Sitecore 5.3.1 code should be like this:
using System;
using Sitecore;
using Sitecore.Configuration;
using Sitecore.Events;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Pipelines.Save;
using Sitecore.Collections;
namespace PreventDouble
{
public class AddedEventHandler
{
public void OnItemAdded(object obj, EventArgs args)
{
Item itm = Event.ExtractParameter(args, 0) as Item;
if (itm.Database.Name == "master")
{
Database database = Factory.GetDatabase("master");
Item[] list = itm.Parent.Axes.SelectItems("*[@@name='"+itm.Name+"']");
if (list == null)
{
return;
}
SitecoreEventArgs evt = args as SitecoreEventArgs;
foreach (Item existItm in list)
{
if ((existItm.ID != itm.ID))
{
Sitecore.Context.ClientPage.ClientResponse.Eval("alert('You cannot create item with the same name!')");
itm.Delete();
evt.Result.Cancel = true;
return;
}
}
}
}
}
}
Prev Next